package cn.xiangyuanpin.dao.impl;

import cn.xiangyuanpin.utils.JdbcUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public abstract class BaseDao {

    private QueryRunner queryRunner=new QueryRunner();

public  int update(String sql,Object...args)  {
    Connection connection= JdbcUtil.getConnection();
    try {
        int a= queryRunner.update(connection,sql,args);
        JdbcUtil.close(connection);
        return a;
    } catch (SQLException e) {
        e.printStackTrace();
    }

    return -1;
}

    public  <T> T queryForOne(Class<T>type, String sql, Object...args)  {
        Connection connection= JdbcUtil.getConnection();
        try {
            T t = queryRunner.query(connection, sql, new BeanHandler<T>(type), args);
            JdbcUtil.close(connection);
            return t;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    public  <T> List<T> queryForList(Class<T>type, String sql, Object...args) {
        Connection connection= JdbcUtil.getConnection();
        try {
            List<T> query = queryRunner.query(connection, sql, new BeanListHandler<T>(type), args);
            JdbcUtil.close(connection);
            return query ;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public  Object queryForSingleValue(String sql, Object...args) {
        Connection connection= JdbcUtil.getConnection();
        try {
            return queryRunner.query(connection,sql,new ScalarHandler(),args);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


}
